package main

import (
	"encoding/base64"
	"fmt"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"project_srvs/user_srv/utils"
	"strings"
)

// 直接将 base64 图片上传到阿里云 OSS
func uploadBase64ToOSS(client *oss.Client, bucketName, objectName, base64Data string) error {
	// 获取指定的 Bucket
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		return fmt.Errorf("获取 Bucket 失败: %v", err)
	}

	// 去掉 base64 编码中的前缀部分，比如 "data:image/png;base64,"
	if strings.HasPrefix(base64Data, "data:image") {
		base64Data = strings.Split(base64Data, ",")[1]
	}

	// 解码 base64 数据
	data, err := base64.StdEncoding.DecodeString(base64Data)
	if err != nil {
		return fmt.Errorf("base64 解码失败: %v", err)
	}

	// 将解码后的数据上传到 OSS
	err = bucket.PutObject(objectName, strings.NewReader(string(data)))
	if err != nil {
		return fmt.Errorf("上传图片到 OSS 失败: %v", err)
	}

	return nil
}

//'oss'=>[
//// TODO 需要修改 （阿里云oss对象存储）
//'accessKeyId'=>'LTAI5tCEvHMbSD7djx53oWmf',
//'accessKeySecret'=>'WE0IgPoqiGzVcPqP4kJJc60lNgbRW5',
//'endpoint'=>'https://oss-cn-qingdao-internal.aliyuncs.com',
//'resourcebucket'=>'sgyuyin-resource',
//'resource_cdn'=>'https://sgyuyin-resource.oss-cn-qingdao.aliyuncs.com/',
//'resource_cdn_host'=>'https://sgyuyin-resource.oss-cn-qingdao.aliyuncs.com/',
//],

func main() {
	//// 配置 OSS 信息
	accessKeyID := "LTAI5tQfySTKpDPGw5T82UEG"
	accessKeySecret := "U8dFsM8IFb77BGNbc2I1RSfCE1Sa1t"
	endpoint := "https://oss-cn-qingdao-internal.aliyuncs.com"
	bucketName := "sgyuyin-resource"
	base64Str := ""
	fileType := 1
	path, ext, err := utils.ProcessBase64Data(fileType, base64Str)
	if err != nil {
		fmt.Println(err)
	}
	objectName := fmt.Sprintf("%s%s.%s", path, utils.GetRandomStr(16, false), ext)

	// 创建 OSS 客户端
	client, err := oss.New(endpoint, accessKeyID, accessKeySecret)
	if err != nil {
		fmt.Println(err)
	}
	//
	// 直接将 base64 数据上传到 OSS
	err = uploadBase64ToOSS(client, bucketName, objectName, base64Str)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(objectName)
}
